package com.example.teaculture.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.example.teaculture.R;
import com.example.teaculture.application.MyApplication;
import com.example.teaculture.fragment.BusinessFragment;
import com.example.teaculture.fragment.EncyclopediaFragment;
import com.example.teaculture.fragment.HeadLinesFragment;
import com.example.teaculture.fragment.KnowledgeFragment;
import com.example.teaculture.fragment.DataFragment;
import com.example.teaculture.model.Favor;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.tabs.TabLayout;
import com.yechaoa.yutils.YUtils;

import java.io.File;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private DrawerLayout mDrawerLayout;
    private NavigationView navigationView;
    private View v;
    private CircleImageView circleImageView;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private List<Fragment> fragments;
    private List<String> titles;
    private Toolbar toolbar;
    private TextView data;
    private TextView userEmail;
    String Email = null;
    private SearchView sv_search;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = findViewById(R.id.toolbar);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); //获取抽屉布局;
        navigationView = (NavigationView) findViewById(R.id.navigation);//活动左侧出侧栏

        v = navigationView.getHeaderView(0);
        //nav头部搜索框
        sv_search = v.findViewById(R.id.sv_search);
        circleImageView = (CircleImageView) v.findViewById(R.id.icon_image);
        tabLayout = (TabLayout) findViewById(R.id.tablayout);
        viewPager = (ViewPager) findViewById(R.id.viewpage);

        userEmail = (TextView) v.findViewById(R.id.text_username);
        Intent intent = getIntent();
        Email = intent.getStringExtra("Email");
        userEmail.setText(Email);

        data = (TextView) v.findViewById(R.id.tv_time);
        String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
        data.setText(currentDateTimeString);
        initViews();
        initDatas();
    }

    private void initDatas() {
        //预加载
        viewPager.setOffscreenPageLimit(fragments.size());

        //设置适配器
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            //选中的ITem
            @Override
            public Fragment getItem(int i) {
                return fragments.get(i);
            }

            //返回Item个数
            @Override
            public int getCount() {
                return fragments.size();
            }
            //设置标题

            @Override
            public CharSequence getPageTitle(int position) {
                return titles.get(position);
            }
        });
        tabLayout.setupWithViewPager(viewPager);
    }


    private void initViews() {
        titles = new ArrayList<>();
        titles.add("头条");
        titles.add("知道");
        titles.add("百科");
        titles.add("经营");
        titles.add("数据");

        fragments = new ArrayList<>();
        fragments.add(new HeadLinesFragment());
        fragments.add(new KnowledgeFragment());
        fragments.add(new EncyclopediaFragment());
        fragments.add(new BusinessFragment());
        fragments.add(new DataFragment());
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onStart() {
        super.onStart();
        /* toolbar.setLogo(R.drawable.icon);//设置图片logo,你可以添加自己的图片*/
        toolbar.setTitle("茶博士");
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            //通过HomeAsUp来让导航按钮显示出来
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.baseline_reorder_black_24dp);   //更改按钮图标
        }
        circleImageView.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                final String[] items = {"相机", "从图库选择"};
                AlertDialog.Builder listDialog =
                        new AlertDialog.Builder(MainActivity.this);
                listDialog.setTitle("编辑头像");
                listDialog.setItems(items, (dialog, which) -> {
                    switch (which) {
                        case 0:
                            // 启动系统相机
                            Intent intent0 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            // 获取拍完后的uri
                            Uri mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg"));
                            intent0.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
                            // 返回结果和标识
                            startActivityForResult(intent0, 0);
                            dialog.dismiss();
                            break;
                        default:
                            //调用系统图库，选择图片
                            Intent intent1 = new Intent(Intent.ACTION_PICK, null);
                            intent1.setDataAndType(MediaStore.Images.Media.INTERNAL_CONTENT_URI, "image/*");
                            // 返回结果和标识
                            startActivityForResult(intent1, 1);
                            dialog.dismiss();
                            break;
                    }
                });
                listDialog.show();
            }
            return false;
        });
        navigationView.setCheckedItem(R.id.nav_edit);//设置第一个默认选中
        //设置菜单项的监听事件
        navigationView.setNavigationItemSelectedListener(menuItem -> {
            mDrawerLayout.closeDrawers();
            switch (menuItem.getItemId()) {
                case R.id.nav_edit:
                    //每个菜单项的点击事件，通过Intent实现点击item简单实现活动页面的跳转。
                    /*Intent intent = new Intent(MainActivity.this, Main2Activity.class);
                    //第二个Main2Activity.class需要你自己new一个 Activity来做出其他功能页面
                    startActivity(intent);*/
                    String name = Email;
                    if (name == null) {
                        Toast.makeText(MainActivity.this, "请登陆后再编辑资料", Toast.LENGTH_SHORT).show();
                    } else {
                        Log.i("TAG", "name为：" + name);
                        Intent intent = new Intent(MainActivity.this, UserDataActivity.class);
                        intent.putExtra("Email", name);
                        startActivity(intent);
                    }

                    break;
                case R.id.nav_favorite:
                    Intent intent_favor = new Intent(MainActivity.this, FavorActivity.class);
                    startActivity(intent_favor);
                    break;
                case R.id.nav_log:
                    Intent intent_history = new Intent(MainActivity.this, HistoryActivity.class);
                    startActivity(intent_history);
                    break;
                case R.id.nav_advice:
                    Intent intent_advice = new Intent(MainActivity.this, AdviceActivity.class);
                    startActivity(intent_advice);
                    break;
                case R.id.nav_version:
                    AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                    dialog.setTitle("版本信息");
                    dialog.setMessage("TeaDoctor 测试版本v1.0");
                    dialog.setCancelable(false);
                    dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    dialog.show();
                    break;
                case R.id.nav_exit:
                    Intent intent_Login = new Intent(MainActivity.this, LoginActivity.class);
                    startActivity(intent_Login);
                    break;
                default:
            }
            return true;
        });
        sv_search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            // 当点击搜索按钮时触发该方法
            @Override
            public boolean onQueryTextSubmit(String query) {
                //关闭软键盘
                YUtils.closeSoftKeyboard();
                //do something
                Intent intent = new Intent(MainActivity.this, SearchActivity.class);
                intent.putExtra("text", sv_search.getQuery().toString());
                startActivity(intent);
                sv_search.setQuery("", false);
                return true;
            }

            // 当搜索内容改变时触发该方法
            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        tabLayout.setupWithViewPager(viewPager);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //获取toolbar菜单项
        getMenuInflater().inflate(R.menu.toolbar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            //R.id.home修改导航按钮的点击事件为打开侧滑栏
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);  //打开侧滑栏
                break;
            case R.id.share:
                Favor favor = MyApplication.getInstance().favor;
                Intent intent_share = new Intent(Intent.ACTION_SEND);
                intent_share.setType("text/plain");
                intent_share.putExtra(Intent.EXTRA_SUBJECT, "分享");
                intent_share.putExtra(Intent.EXTRA_TEXT, "'" + favor.getTitle() + "', " + favor.getUrl());
                intent_share.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(Intent.createChooser(intent_share, getTitle()));
                break;
            case R.id.setting:
                Intent intent_set = new Intent(MainActivity.this, SettingsActivity.class);
                startActivity(intent_set);
                break;
            case R.id.userexit:
                new AlertDialog.Builder(this).setTitle("确认退出吗？")
                        .setIcon(android.R.drawable.ic_dialog_info)
                        .setPositiveButton("确定", (dialog, which) -> {
                            // 点击“确认”后的操作
                            MainActivity.this.finish();
                        })
                        .setNegativeButton("返回", (dialog, which) -> {
                            // 点击“返回”后的操作,这里不设置没有任何操作
                        }).show();
                break;
            default:
        }
        return true;
    }

    @Override
    public void onClick(View v) {

    }
}
